import serial
import time
import keyboard

# 定义串口参数
COM_PORT = 'COM13'
BAUD_RATE = 2400
ser = None

# 定义协议数据列表
pelcod_data=bytearray([0xFF, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00])


##########################################################################
# 硬件相关操作函数

# 打开串口连接
def open_serial():
    global ser
    ser = serial.Serial(COM_PORT, BAUD_RATE, timeout=1)
    print(f"Serial port {COM_PORT} opened.")

# 关闭串口连接
def close_serial():
    if ser:
        ser.close()
        print(f"Serial port {COM_PORT} closed.")
##########################################################################
# 功能函数

# 修改设备地址
def set_devAddr(addr):
    pelcod_data[6] = addr

# 计算校验和
def calculate_checksum():
    checksum = sum(pelcod_data[1:5]) & 0xFF
    pelcod_data[6] = checksum
    
def turn_left_instructions():
    pelcod_data[2:5]=bytearray([0x00,0x02,0x3F,0x00])

def turn_right_instructions():
    pelcod_data[2:5]=bytearray([0x00,0x04,0x3F,0x00])

# 发送命令并接收响应
def send_command(command):
    ser.write(command)
    response = ser.readline().decode().strip()
    print(f"Response: {response}")

##########################################################################
# 云台动作控制

# 设备左转
def turn_left():
    turn_left_instructions()
    calculate_checksum()
    send_command(pelcod_data)

# 设备右转
def turn_right():
    turn_right_instructions()
    calculate_checksum()
    send_command(pelcod_data)

# 设备停止
def turn_stop():
    pelcod_data[2:5]=bytearray([0x00,0x00,0x00,0x00])
    calculate_checksum()
    send_command(pelcod_data)

# 设置预置点
def set_preset(preset_number):
    command = f"PELCOD,PRESET,SET,{preset_number}\r\n"
    send_command(command)

# 调用预置点
def call_preset(preset_number):
    command = f"PELCOD,PRESET,CALL,{preset_number}\r\n"
    send_command(command)

# 删除预置点
def delete_preset(preset_number):
    command = f"PELCOD,PRESET,DELETE,{preset_number}\r\n"
    send_command(command)

##########################################################################

# 键盘监听回调函数
def on_key_press(event):
    if event.name == 'left':
        turn_left()
    elif event.name == 'right':
        turn_right()
    else :
        turn_stop()

# 主程序入口
if __name__ == '__main__':
    # 打开串口连接
    open_serial()

    # 注册键盘监听回调函数
    keyboard.on_press(on_key_press)

    # 保持程序运行，直到按下Esc键退出
    keyboard.wait('esc')

    # 关闭串口连接
    close_serial()
